package com.suxin.nio;

import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * @Classname ScatteringAndGattheringTest
 * @Description [ TODO ]
 * @Author Tang
 * @Date 2020/12/27 20:48
 * @Created by ASUS
 */
public class ScatteringAndGatheringTest {

    /**
     *分散写入
     *
     */
    public static void main(String[] args) throws Exception{

        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 绑定端口
        serverSocketChannel.bind(new InetSocketAddress(9000));
        // 接收 client
        SocketChannel socketChannel = serverSocketChannel.accept();
        // 分散
        ByteBuffer[] buffers = new ByteBuffer[2];
        buffers[0] = ByteBuffer.allocate(5);
        buffers[1] = ByteBuffer.allocate(5);

        while (true) {
            long read = socketChannel.read(buffers);
            System.out.println("接收到的个数为：" + read);

            Arrays.asList(buffers).forEach((buffer) -> {
                buffer.flip();
                System.out.println("receive：--->" + new String((buffer.array())));
            });

            // 写回去
            socketChannel.write(buffers);

            Arrays.asList(buffers).forEach(Buffer::clear);
        }

    }

}